const { URL } = require("../../config/keys");
const express = require("express");
const router = express.Router();
//导入数据库的视图
const Bike = require("../../models/Bike");
const Rent = require("../../models/Rent");

router.post("/create", (req, res) => {
  //判断数据库中是否有email
  Bike.findOne({
    name: req.body.name,
  }).then((user) => {
    if (user)
      res.json({
        success: false,
        msg: "该类型已经存在",
      });
    else {
      const type = new Bike({
        name: req.body.name,
        state: req.body.state,
        money: req.body.money,
        type_id: req.body.type_id
      });
      type
        .save()
        .then((user) =>
          res.json({
            success: true,
            msg: "保存成功",
          })
        )
        .catch((err) => console.log(err));
    }
  });
});

router.get("/getBike", (req, res) => {
  Bike.aggregate(
    [
      {
        $lookup: {
          from: 'types',
          localField: 'type_id',
          foreignField: '_id',
          as: 'types',
        },
      },
      {
        //展示的数据
        $project: {
          _id: 1,
          name: 1,
          state: 1,
          money: 1,
          date: 1,
          types: 1,
          type_id: 1
        },
      },

    ],
    (err, docs) => {
      docs.forEach(element => {
        if (element.types[0] && element.types[0].name) {
          element.typeName = element.types[0].name
          element.type_id = element.types[0]._id
          delete element.types
        }

      });
      return res.json({
        success: true,
        result: docs,
      })
    }
  )
});

router.get("/scrapBike", (req, res) => {
  Bike.aggregate(
    [
      {
        $match: {
          state: false
        },
      },
      {
        $lookup: {
          from: 'types',
          localField: 'type_id',
          foreignField: '_id',
          as: 'types',
        },
      },
      {
        //展示的数据
        $project: {
          _id: 1,
          name: 1,
          state: 1,
          money: 1,
          date: 1,
          types: 1,
          type_id: 1
        },
      },

    ],
    (err, docs) => {
      docs.forEach(element => {
        if (element.types[0] && element.types[0].name) {
          element.typeName = element.types[0].name
        }
        delete element.types
      });
      return res.json({
        success: true,
        result: docs,
      })
    }
  )


});

router.get("/deleteBike/:id", (req, res) => {
  Bike.remove({ _id: req.params.id }).then((type) => {
    res.json({
      success: true,
      msg: "删除成功",
    });
  });
});



router.post('/update', (req, res) => {
  Bike.updateOne({ _id: req.body._id }, {
    ...req.body
  }).then(response => {
    return res.json({
      success: true,
      mas: '修改成功'
    })
  })
})

// 空闲自行车
router.get("/idleList", (req, res) => {
  Bike.aggregate(
    [
      {
        $lookup: {
          from: "rents",
          localField: "_id",
          foreignField: "bike_id",
          as: "rents",
        },
      },
      {
        //展示的数据
        $project: {
          _id: 1,
          end_data: 1,
          start_date: 1,
          rents: 1,
          name: 1,
          state: 1,
          money: 1,
          date: 1,
        },
      },
      // {
      //   $unwind: {
      //     // 拆分子数组
      //     path: "$rents",
      //     preserveNullAndEmptyArrays: true, // 空的数组也拆分
      //   },
      // },
      {
        $match: {
          state: {
            $ne: false,
          },
          // "rents.end_data": {
          //   $ne: null,
          // },
        },
      },
    ],
    (err, docs) => {
      if (err) {
        return console.log(err);
      }
      let data = docs.filter((element) => {
        if (element.rents.length !== 0) {
          if (
            element.rents.find((rent) => {
              if (!rent.end_data) {
                return true;
              }
            })
          ) {
            delete element;
          } else {
            delete element.rents;
            return element;
          }
        } else {
          delete element.rents;
          return element;
        }
      });

      res.json({
        success: true,
        result: data,
      });
    }
  );
});


router.get("/searchList/:name", (req, res) => {
  Bike.aggregate(
    [
      {
        $lookup: {
          from: "rents",
          localField: "_id",
          foreignField: "bike_id",
          as: "rents",
        },
      },
      {
        //展示的数据
        $project: {
          _id: 1,
          end_data: 1,
          start_date: 1,
          rents: 1,
          name: 1,
          state: 1,
          money: 1,
          date: 1,
        },
      },
      // {
      //   $unwind: {
      //     // 拆分子数组
      //     path: "$rents",
      //     preserveNullAndEmptyArrays: true, // 空的数组也拆分
      //   },
      // },
      {
        $match: {
          state: {
            $ne: false,
          },
          name: req.params.name
          // "rents.end_data": {
          //   $ne: null,
          // },
        },
      },
    ],
    (err, docs) => {
      if (err) {
        return console.log(err);
      }
      let data = docs.filter((element) => {
        if (element.rents.length !== 0) {
          if (
            element.rents.find((rent) => {
              if (!rent.end_data) {
                return true;
              }
            })
          ) {
            delete element;
          } else {
            delete element.rents;
            return element;
          }
        } else {
          delete element.rents;
          return element;
        }
      });

      res.json({
        success: true,
        result: data,
      });
    }
  );
});
module.exports = router;
